# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-04 23:30
# File     : state_manager.py
# Project  : codebuddy_craft
# Desc     : 状态管理
# frontend/utils/state_manager.py
import streamlit as st
from typing import Dict, Any, Optional, List


class StateManager:
    """前端状态管理器"""
    
    def __init__(self):
        self._init_session_state()
    
    def _init_session_state(self):
        """初始化会话状态"""
        
        # 基础状态
        defaults = {
            'current_project': None,
            'selected_file': None,
            'user_id': 'demo_user',  # 演示用户ID
            'show_create_project_dialog': False,
            'show_create_file_dialog': False,
            'clipboard': '',
            'recent_files': [],
            'chat_histories': {},
            'editor_settings': {
                'theme': 'monokai',
                'font_size': 14,
                'tab_size': 4,
                'auto_save': True,
                'show_line_numbers': True
            }
        }
        
        for key, value in defaults.items():
            if key not in st.session_state:
                st.session_state[key] = value
    
    # 项目管理
    def get_current_project(self) -> Optional[Dict[str, Any]]:
        """获取当前项目"""
        return st.session_state.get('current_project')
    
    def set_current_project(self, project: Optional[Dict[str, Any]]):
        """设置当前项目"""
        st.session_state['current_project'] = project
    
    def clear_current_project(self):
        """清除当前项目"""
        st.session_state['current_project'] = None
    
    # 文件管理
    def get_selected_file(self) -> Optional[Dict[str, Any]]:
        """获取选中的文件"""
        return st.session_state.get('selected_file')
    
    def set_selected_file(self, file: Optional[Dict[str, Any]]):
        """设置选中的文件"""
        st.session_state['selected_file'] = file
        
        # 添加到最近文件列表
        if file:
            self._add_to_recent_files(file)
    
    def _add_to_recent_files(self, file: Dict[str, Any]):
        """添加到最近文件列表"""
        recent_files = st.session_state.get('recent_files', [])
        
        # 移除重复项
        recent_files = [f for f in recent_files if f.get('id') != file.get('id')]
        
        # 添加到开头
        recent_files.insert(0, file)
        
        # 限制数量
        recent_files = recent_files[:10]
        
        st.session_state['recent_files'] = recent_files
    
    def get_recent_files(self) -> List[Dict[str, Any]]:
        """获取最近文件列表"""
        return st.session_state.get('recent_files', [])
    
    # 对话管理
    def get_chat_history(self, project_id: str) -> List[Dict[str, Any]]:
        """获取聊天历史"""
        chat_histories = st.session_state.get('chat_histories', {})
        return chat_histories.get(project_id, [])
    
    def add_chat_message(self, project_id: str, message: Dict[str, Any]):
        """添加聊天消息"""
        chat_histories = st.session_state.get('chat_histories', {})
        
        if project_id not in chat_histories:
            chat_histories[project_id] = []
        
        chat_histories[project_id].append(message)
        st.session_state['chat_histories'] = chat_histories
    

    def clear_chat_history(self, project_id: str):
        """清除聊天历史"""
        chat_histories = st.session_state.get('chat_histories', {})
        if project_id in chat_histories:
            chat_histories[project_id] = []
            st.session_state['chat_histories'] = chat_histories
    
    # 编辑器设置
    def get_editor_settings(self) -> Dict[str, Any]:
        """获取编辑器设置"""
        return st.session_state.get('editor_settings', {})
    
    def update_editor_setting(self, key: str, value: Any):
        """更新编辑器设置"""
        editor_settings = st.session_state.get('editor_settings', {})
        editor_settings[key] = value
        st.session_state['editor_settings'] = editor_settings
    
    # 对话框状态
    def get_show_create_project_dialog(self) -> bool:
        """获取创建项目对话框显示状态"""
        return st.session_state.get('show_create_project_dialog', False)
    
    def set_show_create_project_dialog(self, show: bool):
        """设置创建项目对话框显示状态"""
        st.session_state['show_create_project_dialog'] = show
    
    def get_show_create_file_dialog(self) -> bool:
        """获取创建文件对话框显示状态"""
        return st.session_state.get('show_create_file_dialog', False)
    
    def set_show_create_file_dialog(self, show: bool):
        """设置创建文件对话框显示状态"""
        st.session_state['show_create_file_dialog'] = show
    
    # 剪贴板
    def get_clipboard(self) -> str:
        """获取剪贴板内容"""
        return st.session_state.get('clipboard', '')
    
    def set_clipboard(self, content: str):
        """设置剪贴板内容"""
        st.session_state['clipboard'] = content
    
    # 用户设置
    def get_user_id(self) -> str:
        """获取用户ID"""
        return st.session_state.get('user_id', 'demo_user')
    
    def set_user_id(self, user_id: str):
        """设置用户ID"""
        st.session_state['user_id'] = user_id
    
    # 缓存管理
    def clear_cache(self, cache_key: Optional[str] = None):
        """清除缓存"""
        if cache_key:
            if cache_key in st.session_state:
                del st.session_state[cache_key]
        else:
            # 清除所有缓存
            cache_keys = [key for key in st.session_state.keys() if key.startswith('cache_')]
            for key in cache_keys:
                del st.session_state[key]
    
    def set_cache(self, key: str, value: Any):
        """设置缓存"""
        st.session_state[f'cache_{key}'] = value
    
    def get_cache(self, key: str) -> Any:
        """获取缓存"""
        return st.session_state.get(f'cache_{key}')
    
    # 状态重置
    def reset_all(self):
        """重置所有状态"""
        for key in list(st.session_state.keys()):
            del st.session_state[key]
        self._init_session_state()


# 全局状态管理器实例
def get_state_manager() -> StateManager:
    """获取全局状态管理器实例"""
    if 'state_manager' not in st.session_state:
        st.session_state.state_manager = StateManager()
    return st.session_state.state_manager